﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Web.Controllers
{
    public class DocumentController : AsyncCommonController
    {
        public DocumentController() { }


        public ActionResult Outgoing(string search)
        {
            return View();
        }

        public ActionResult OutgoingInvoices(Search search = null)
        {
            var searchList = new List<String>();
            var searchString = String.Empty;
            string userDateFormat = "dd.MM.yyyy";
            DateTime fromDate, toDate;

            if (search != null)
            {
                if (search.CUSTOMER_GUID.HasValue)
                    searchList.Add("CUSTOMER_GUID eq guid'" + search.CUSTOMER_GUID.Value.ToString() + "'");

                if (search.LOCATION_GUID.HasValue)
                    searchList.Add("LOCATION_GUID eq guid'" + search.LOCATION_GUID.Value.ToString() + "'");

                if (DateTime.TryParseExact(search.DOC_DATE_START, userDateFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out fromDate))
                {
                    searchList.Add("DOC_DATE ge DateTime'" + fromDate.ToString("yyyy-MM-dd") + "'");
                }

                if (DateTime.TryParseExact(search.DOC_DATE_END, userDateFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out toDate))
                {
                    searchList.Add("DOC_DATE le DateTime'" + toDate.ToString("yyyy-MM-dd") + "'");
                }

                if (!String.IsNullOrEmpty(search.DOC_NUMBER))
                    searchList.Add("DOC_NUMBER eq '" + search.DOC_NUMBER + "'");

                if (String.IsNullOrEmpty(search.IS_ALL))
                    searchList.Add("CUSTOMER_DOC_ID eq null");
            }
            else
            {
                searchList.Add("CUSTOMER_DOC_ID eq null");
            }

            searchString = String.Join(" and ", searchList);
            
            var data = EdexContext.GetOutgoingInvoices(searchString);
            return PartialView(data);
        }

        public ActionResult OutgoingInvoice(Guid? id = null)
        {
            if (id.HasValue)
            {
                var data = EdexContext.GetOutgoingInvoice(id.ToString());
                return View("OutgoingInvoiceEdit", data);
            }
            else
            {
                return View("OutgoingInvoiceNew");
            }
        }

        public ActionResult OutgoingInvoiceDetails(Guid? id = null)
        {
            if (id.HasValue)
            {
                var data = EdexContext.GetOutgoingInvoiceLine(id.Value.ToString());
                return View("OutgoingInvoiceDetailsEdit", data);
            }
            else
            {
                return View("OutgoingInvoiceDetailsNew");
            }
        }

        
        public ActionResult Incoming(string search)
        {
            return View();
        }

        public ActionResult IncomingInvoices(Search search = null)
        {
            var searchList = new List<String>();
            var searchString = String.Empty;
            string userDateFormat = "dd.MM.yyyy";
            DateTime fromDate, toDate;

            if (search != null)
            {
                if (search.CUSTOMER_GUID.HasValue)
                    searchList.Add("COMPANY_GUID eq guid'" + search.CUSTOMER_GUID.Value.ToString() + "'");

                if (search.LOCATION_GUID.HasValue)
                    searchList.Add("LOCATION_GUID eq guid'" + search.LOCATION_GUID.Value.ToString() + "'");

                if (DateTime.TryParseExact(search.DOC_DATE_START, userDateFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out fromDate))
                {
                    searchList.Add("DOC_DATE ge DateTime'" + fromDate.ToString("yyyy-MM-dd") + "'");
                }

                if (DateTime.TryParseExact(search.DOC_DATE_END, userDateFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out toDate))
                {
                    searchList.Add("DOC_DATE le DateTime'" + toDate.ToString("yyyy-MM-dd") + "'");
                }

                if (!String.IsNullOrEmpty(search.DOC_NUMBER))
                    searchList.Add("DOC_NUMBER eq '" + search.DOC_NUMBER + "'");

                if (String.IsNullOrEmpty(search.IS_ALL))
                    searchList.Add("DOC_ID eq null");
            }
            else
            {
                searchList.Add("DOC_ID eq null");
            }

            searchString = String.Join(" and ", searchList);

            var data = EdexContext.GetIncomingInvoices(searchString);
            return PartialView(data);
        }

        public ActionResult IncomingInvoice(Guid id)
        {
            var data = EdexContext.GetIncomingInvoice(id.ToString());
            return PartialView(data);
        }

        public ActionResult IncomingInvoiceLine(Guid id)
        {
            var data = EdexContext.GetIncomingInvoiceLine(id.ToString());
            return PartialView(data);
        }


        [HttpPost]
        public ActionResult SaveOutgoingInvoice(EdexApiClient.Invoices invoice)
        {
            if (invoice.GUID_RECORD != Guid.Empty && invoice.GUID_RECORD != null)
                EdexContext.UpdateInvoice(invoice);
            else
                EdexContext.AddInvoice(invoice);
            
            return Content("OK");
        }

        [HttpPost]
        public ActionResult SaveOutgoingInvoiceLine(EdexApiClient.InvoiceLines line)
        {
            if (line.GUID_RECORD != Guid.Empty && line.GUID_RECORD != null)
                EdexContext.UpdateInvoiceDetails(line);
            else
                EdexContext.AddInvoiceDetails(line);

            return Content("OK");
        }

        [HttpPost]
        public ActionResult DeleteOutgoingInvoice(string id)
        {
            EdexContext.DeleteInvoice(id);
            return Content("OK");
        }

        [HttpPost]
        public ActionResult DeleteOutgoingInvoiceLine(string id)
        {
            EdexContext.DeleteInvoiceDetails(id);
            return Content("OK");
        }

        [HttpGet]
        public ActionResult Upload()
        {
            return View();
        }

        [HttpPost]
        [ActionName("Upload")]
        public async Task<ActionResult> UploadFile(CancellationToken cancellationToken)
        {
            for (var i = 0; i < Request.Files.Count; i++)
            {
                var result = await EdexContext.UploadOutgoingInvoices(Request.Files[i].InputStream, Request.Files[i].FileName);
                
                if (result.StatusCode != System.Net.HttpStatusCode.OK && result.StatusCode != System.Net.HttpStatusCode.NoContent)
                {
                    var js = new System.Web.Script.Serialization.JavaScriptSerializer();
                    var data = js.Deserialize<EdexApiClient.ExceptionInfo>(result.Content.ReadAsStringAsync().Result);

                    throw new Exception(data.ExceptionMessage);
                }
          
            }

            var document = EdexContext.GetLastOutgoingInvoices().SingleOrDefault();
            if (document != null)
            {
                /// http://1edex.com/document/outgoing/#!/invoice/bf18ee53-a064-4687-ace1-5ea095045c7c
                string url = "/document/Outgoing/#!/invoice/" + document.GUID_RECORD.ToString();
                return Redirect(url);
            }

            return View("UploadComplete");
        }

        [HttpPost]
        [ActionName("UploadSync")]
        public ActionResult UploadSync()
        {
            for (var i = 0; i < Request.Files.Count; i++)
            {
                var result = EdexContext.UploadOutgoingInvoicesSync(Request.Files[i].InputStream, Request.Files[i].FileName);

                if (result.StatusCode != System.Net.HttpStatusCode.OK &&
                    result.StatusCode != System.Net.HttpStatusCode.NoContent)
                {
                    var js = new System.Web.Script.Serialization.JavaScriptSerializer();
                    var data = js.Deserialize<EdexApiClient.ExceptionInfo>(result.Content.ReadAsStringAsync().Result);

                    throw new Exception(data.ExceptionMessage);
                }
            }

            var document = EdexContext.GetLastOutgoingInvoices().SingleOrDefault();
            if (document != null)
            {
                /// http://1edex.com/document/outgoing/#!/invoice/bf18ee53-a064-4687-ace1-5ea095045c7c
                string url = "/document/Outgoing/#!/invoice/" + document.GUID_RECORD.ToString();
                return Redirect(url);
            }

            return View("UploadComplete");
        }

        public ActionResult Download(Guid[] GUID_RECORD)
        {
            EdexContext.CheckConstraints();
            var data = EdexContext.GetIncomingInvoicesCommerceML(GUID_RECORD);
            return File(data, "application/xml", "commerceML.xml");
        }

        public class Search
        {
            public Guid? CUSTOMER_GUID { get; set; }
            public Guid? LOCATION_GUID { get; set; }
            public String DOC_DATE_START { get; set; }
            public String DOC_DATE_END { get; set; }
            public String DOC_NUMBER { get; set; }
            public String IS_ALL { get; set; }
        }

    }
}
